import html2canvas from 'html2canvas'

/**
 * 根据window.devicePixelRatio获取像素比
 */
function DPR() {
  if (window.devicePixelRatio && window.devicePixelRatio > 1) {
    return window.devicePixelRatio
  }
  return 1
}
/**
 *  将传入值转为整数
 */
function parseValue(value) {
  return parseInt(value, 10)
}
/**
 * 绘制canvas
 */
function drawCanvas(selector) {
  return new Promise((resolve, reject) => {
    // 获取想要转换的 DOM 节点
    const dom = document.querySelector(selector)
    const box = window.getComputedStyle(dom)
    // DOM 节点计算后宽高
    const width = parseValue(box.width)
    const height = parseValue(box.height)
    // 创建自定义 canvas 元素
    var canvas = document.createElement('canvas')
    // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
    canvas.width = width
    canvas.height = height

    let x = width
    let y = height
    html2canvas(dom, { allowTaint: true, useCORS: true }).then(function(canvas) {
      document.body.appendChild(canvas)
      resolve(canvas.toDataURL('image/png'))
    })
    // html2canvas(dom, { canvas, allowTaint: true, useCORS: true }).then(c => {
    //   resolve(getCanvasImg(c, x, y))
    // })
  })
}

/**
 * 图片转base64格式
 */
function getCanvasImg(canvas, x, y) {
  let image = {}
  image.width = x
  image.height = y
  image.src = canvas.toDataURL('image/png')
  return image
}

export { drawCanvas }
